# coding=utf-8
import os

import time

from jproperties import Properties

from core.sqlite3db.SqliteInner import SqliteInner
from core.sqlite3db.SqliteSql import SqliteSql
from tools.OperationError import OperationError
from webapp.config import Config


class Users:
    def saveUserRemInfo(self, name, password, isUsername='N', isPassword='N'):

        bz = 0
        if isUsername == 'Y' and isPassword == 'Y':
            bz = 2  # 都记住
        elif isUsername == 'Y' and isPassword == 'N':
            bz = 1  # 记住用户
        elif isUsername == 'N' and isPassword == 'N':
            bz = 0  # 不记录

        # 获取路径
        filename = Config.ROOT_PATH + os.sep + r"initconfig" + os.sep + "master.properties"
        print(filename)
        p = Properties()
        file_dir = os.path.split(filename)[0]
        if not os.path.isdir(file_dir):
            os.makedirs(file_dir)
        # 已存在文件
        if os.path.exists(filename):
            props = p.load(filename)
            print(props)
            arrs = props.get(Config.KEY_USER_REM, []);
            if len(arrs) > 0:
                arrs = eval(arrs)
            else:
                arrs = []
            isFind = False
            for i in range(len(arrs)):
                arr = arrs[i]
                if arr["name"] == name:
                    arrs.remove(arr)
                    if bz == 1 or bz == 2:
                        user = {}
                        user["name"] = name
                        if bz == 2:
                            user["password"] = password
                        user["time"] = time.time()
                        arrs.append(user)
                    isFind = True
                    break
            if isFind == False:
                if bz == 1 or bz == 2:
                    user = {}
                    user["name"] = name
                    if bz == 2:
                        user["password"] = password
                    user["time"] = time.time()
                    arrs.append(user)

            props.__setitem__(Config.KEY_USER_REM, Properties.escape(str(arrs)))
            # 更新记住状态
            isUserRem = {}
            isUserRem["isUsername"] = isUsername
            isUserRem["isPassword"] = isPassword
            props.__setitem__(Config.KEY_IS_USER_REM, Properties.escape(str(isUserRem)))

            # 全部遍历下
            for prop in props:
                props.__setitem__(prop, Properties.escape(props[prop]))
            # 保存文件
            props.save(filename)
        else:
            arrs = []
            if bz == 1 or bz == 2:
                user = {}
                user["name"] = name
                if bz == 2:
                    user["password"] = password
                user["time"] = time.time()
                arrs.append(user)

            p.__setitem__(Config.KEY_USER_REM, Properties.escape(str(arrs)))
            # 更新记住状态
            isUserRem = {}
            isUserRem["isUsername"] = isUsername
            isUserRem["isPassword"] = isPassword
            p.__setitem__(Config.KEY_IS_USER_REM, Properties.escape(str(isUserRem)))

            # 保存文件
            p.save(filename)

    def getUserRemInfo(self):

        filename = Config.ROOT_PATH + os.sep + r"initconfig" + os.sep + "master.properties"
        print(filename)
        p = Properties()
        props = p.load(filename)
        print(props)
        arrs = props.get(Config.KEY_USER_REM, []);
        if len(arrs) > 0:
            arrs = eval(arrs)
        else:
            arrs = []

        return arrs

    def getIsUserRem(self):

        filename = Config.ROOT_PATH + os.sep + r"initconfig" + os.sep + "master.properties"
        print(filename)
        p = Properties()
        props = p.load(filename)
        print(props)
        arr = props.get(Config.KEY_IS_USER_REM, {});
        if len(arr) > 0:
            arr = eval(arr)
        else:
            arr = {}

        return arr

    def saveUsersInfo(self, data):

        if len(data) <= 0:
            return

        salersInfo = data.get("EMPSINFO", None)
        usersInfo = data.get("USERSINFO", None)

        sqliteinit = SqliteInner()
        sqliteinit.setConnetion("master")

        # 营业员
        if None != salersInfo:
            # 先删除
            sqliteinit.execute(str(SqliteSql.deleteEmps))
            for saler in salersInfo:
                print(saler)
                ID = saler.get("ID", None)
                ECODE = saler.get("ECODE", None)
                ENUMNO = saler.get("ENUMNO", None)
                ENAME = saler.get("ENAME", None)
                CP_C_STORE_ID = saler.get("CP_C_STORE_ID", None)
                # 再新增
                sqliteinit.execute(str(SqliteSql.deleteEmps))
                sqliteinit.execute(str(SqliteSql.insertEmps), (ID, ECODE, ENUMNO, ENAME, CP_C_STORE_ID))

        # 用户
        if None != usersInfo:
            # 先删除
            sqliteinit.execute(str(SqliteSql.deleteUsers))
            for user in usersInfo:
                print(user)
                ID = user.get("ID", None)
                ECODE = user.get("ECODE", None)
                PASSWORD = user.get("SIGNKEY", None)
                ENAME = user.get("ENAME", None)
                CP_C_STORE_ID = user.get("CP_C_STORE_ID", None)
                CP_C_DISTRIB_ID = user.get("CP_C_DISTRIB_ID", None)
                # 再新增
                sqliteinit.execute(str(SqliteSql.insertUsers),
                                   (ID, ECODE, PASSWORD, ENAME, CP_C_STORE_ID, CP_C_DISTRIB_ID))

        sqliteinit.closedb()

    def getSalers(self):

        sqliteinit = SqliteInner()
        try:
            sqliteinit.setConnetion("master")
            list = sqliteinit.execute_list(str(SqliteSql.getEmps))

        except Exception as e:
            raise e

        finally:
            sqliteinit.closedb()

        return list

    def getUser(self, ecode=None):

        sqliteinit = SqliteInner()
        try:
            sqliteinit.setConnetion("master")
            list = sqliteinit.execute_list(str(SqliteSql.getUsers % ecode))
            if list != None and len(list) > 0:
                res = list[0]
            else:
                raise OperationError(-1, "数据为空！")

        except Exception as e:
            raise e

        finally:
            sqliteinit.closedb()

        return res


if __name__ == "__main__":
    s = Users()
    # s.saveUserInfo("周城", "asdasdssdsd", 'Y', 'Y')
    # print(s.saveUserInfo())
    ret = s.getUser();
    print(type(ret))
    print(ret)
    # isUser = s.getIsUserRem()
    # print(type(isUser))
    # print(isUser)
